<template>
  <div>
    <el-card class="table-card">
      <div slot="header">
        <h4>{{isEdit ? '编辑钢材类厂直标准' : '新增钢材类厂直标准'}}</h4>
      </div>
      <BtnRender :render="renderBtnsBar" />
      <el-row>
        <SkusTable
          showActionCol
          :actionColWidth="80"
          :columns="tableInfo.columns"
          :loading="tableInfo.loading"
          :dataSource="tableInfo.list"
          :actionRender="tableBtnAction"
        />
      </el-row>
    </el-card>
  </div>
</template>
<script>
import SkusTable from '@/components/skusTable';
import { createExcelByExport } from '@/utils/bizUtils';
import {
  queryStandardDetailByIdsService,
  queryStandardDetailByRecordService,
  exportFactoryStandardTempService,
  submitStantardService,
} from '@/api/sourcing/factoryStandard';
import {
  queryAllProvinceAndCityService
} from '@/api/sourcing/public';
import BtnRender from '@/components/JSXRender/BtnRender';
import { getBtnsBar } from '@/utils/getBtnsRender';
import { ERRORS_COLUMN } from './constants';
import { PROVINCE_CITY_LIST } from '../constants';

const CONFIG_TYPE = 2; // 配置类型
export default {
  components: {
    SkusTable,
    BtnRender,
  },
  data () {
    return {
      SelectCategory: () => import('@/pages/sourcing/components/CategorySearch'),
      key: 1,
      submitLoading: false,
      importLoading: false,
      exportLoading: false,
      idList: [],
      recordId: '',
      tableInfo: {
        loading: false,
        list: [],
        columns: []
      },
      rangeInfoOptions: [],
      cascaderProps: {
        multiple: true,
        label: 'name',
        value: 'code',
        id: 'id',
      },
      allAreaListLength: 0,
    };
  },
  computed: {
    // 编辑来源 0 审批完成 1 待审批
    sourceType () {
      if (this.idList.length !== 0) {
        return 0
      }
      if (this.recordId) {
        return 1
      }
      return 0
    },
    isEmpty () {
      return this.tableInfo.list.length === 0
    },
    isEdit () {
      return this.idList.length !== 0 || this.recordId;
    },
    ids () {
      if (this.isEdit && this.idList.length !== 0) {
        return this.tableInfo.list.map(item => item.factoryDirectConfigId)
      }
      if (this.isEdit && this.recordId) {
        return this.tableInfo.list.map(item => item.factoryDirectConfigAuditId)
      }
      return []
    }
  },
  mounted () {
    this.initTableColumns();
    this.initTableData();
    this.getAreaTreeList();
  },
  methods: {
    // 获取省市
    async getAreaTreeList () {
      const res = await queryAllProvinceAndCityService(
        {},
        state => { this.tableInfo.loading = state }
      )
      if (res?.data) {
        const { data } = res
        this.rangeInfoOptions = [{
          id: '10',
          code: 10,
          name: '全国',
          children: data
        }]
        const areaList = data.map(item => item.children)
        this.allAreaListLength = areaList.flat().length
      }
    },
    // 初始化表格数据
    initTableData () {
      const { idList } = this.$route.params;
      const { auditRecordId } = this.$route.query;
      if (idList) {
        this.idList = idList;
        this.getTableDataByIds();
      }
      if (auditRecordId) {
        this.recordId = auditRecordId;
        this.getTableDataByRecordId();
      }
      if (!this.isEdit) {
        this.handleAdd(1)
      }
    },
    // 初始化表头
    initTableColumns () {
      this.tableInfo.columns = [
        {
          title: '四级类名称',
          key: 'categoryName',
          required: true,
          width: 100,
          render: (h, { row, index }) => {
            if (!this.recordId && this.isEdit) {
              return <span>{row.categoryName}</span>
            }
            const SelectCategory = this.SelectCategory
            return <SelectCategory
              setName={true}
              value={row.categoryName}
              brandId={row.brandId}
              onOnSelected={ (data) => { this.handleCategorySelected(data, row, index) }}
            />
          }
        },
        {
          title: '四级类代码',
          key: 'categoryCode',
          required: true,
        },
        {
          title: '可直送金额（万元）',
          key: 'directDeliveryAmount',
          required: true,
          width: 120,
          type: 'inputNumSpecial',
          minVal: 1,
        },
        {
          title: '可直送范围',
          key: 'provinceCityList',
          required: true,
          width: 246,
          render: (h, { row, index }) => {
            return <el-cascader
              style="width: 100%"
              v-model={row.provinceCityList}
              size="small"
              on-change={(val) => this.handleNodeChange(val, row)}
              placeholder="请选择直送范围"
              options={this.rangeInfoOptions}
              props={{ props: this.cascaderProps }}
              filterable
              show-all-levels={false}
              collapse-tags
            ></el-cascader>
          }
        },
        {
          title: '费用比例（%）',
          key: 'expenseRatio',
          type: 'inputNumSpecial',
          precision: 2,
          minVal: 0,
          required: true,
          width: 120,
        },
        {
          title: '备注',
          key: 'remark',
          type: 'input',
          width: 150,
        },
      ]
    },
    // 直送范围节点选择
    handleNodeChange (value, row) {
      const cityCodeList = value.map(item => item[2])
      row.cityCodeList = cityCodeList;
      row.directDeliveryRange = cityCodeList.length == this.allAreaListLength ? 1 : 2;
    },
    // 初始化操作按钮
    renderBtnsBar (h) {
      const btns = [
        {
          label: '增加行',
          method: () => { this.handleAdd(1) },
        },
        {
          label: '增加10行',
          method: () => { this.handleAdd(10) },
        },
        {
          label: '增加50行',
          method: () => { this.handleAdd(50) },
        },
        {
          label: '模板导入',
          action: 'srm-api/factoryDirectConfig/importTemplate',
          methods: { handleUploadSuccess: this.handleUploadSuccess },
          isImport: true,
          data: {
            idList: this.ids,
            type: this.sourceType,
            configType: CONFIG_TYPE
          },
          loadingFn: state => { this.importLoading = state },
        },
        {
          label: '模板导出',
          method: this.handleExportTemplate,
          loading: this.exportLoading,
        },
        {
          label: '提交',
          method: this.handleSubmit,
          loading: this.submitLoading,
          disabled: this.isEmpty
        },
        {
          label: '取消',
          method: this.handleBack,
        },
      ];
      if (this.isEdit) {
        btns.splice(0, 3)
      }
      btns.forEach(item => {
        item.size = 'medium'
      })
      return getBtnsBar(h, btns);
    },
    // 渲染表格操作栏按钮
    tableBtnAction (h, { index, row }) {
      return (
        <div class="table-action">
          <el-button type="text" onClick={() => this.handleDelete(index)}>
            删除
          </el-button>
        </div>
      );
    },
    // 获取表格数据通过idList
    async getTableDataByIds () {
      const res = await queryStandardDetailByIdsService(
        {
          configType: CONFIG_TYPE,
          idList: this.idList,
        },
        state => { this.tableInfo.loading = state }
      );
      if (res?.data) {
        const { data } = res
        this.formatTableData(data)
      }
    },
    // 获取表格数据通过单据号
    async getTableDataByRecordId () {
      const res = await queryStandardDetailByRecordService(
        { auditRecordId: this.recordId },
        state => { this.tableInfo.loading = state }
      );
      if (res?.data) {
        const { data } = res
        this.formatTableData(data)
      }
    },
    // 格式化表格数据
    formatTableData (data) {
      data.forEach(item => {
        if (item.provinceCityList == null && item.directDeliveryRange == 1) {
          item.provinceCityList = PROVINCE_CITY_LIST
        }
      })
      this.tableInfo.list = data
    },
    // 导入成功
    handleUploadSuccess (res) {
      this.importLoading = false;
      const { code, data, msg } = res;
      if (code == 200) {
        this.formatTableData(data)
      } else {
        this.$message.error(msg);
      }
    },
    // 导出信息数据
    async handleExportTemplate () {
      const res = await exportFactoryStandardTempService(
        {
          idList: this.ids,
          type: this.sourceType,
          configType: CONFIG_TYPE
        },
        state => { this.exportLoading = state; }
      );
      createExcelByExport({ res, excelTitle: '钢材类厂直标准模板' });
    },
    // 选择品类
    handleCategorySelected (data = {}, row) {
      const { categoryNo = '', categoryName = '' } = data || {}
      row.categoryName = categoryName
      row.categoryCode = categoryNo
    },
    // 新增行
    handleAdd (length) {
      for (let i = 0; i < length; i++) {
        this.tableInfo.list.push(
          {
            key: this.key++,
            configType: CONFIG_TYPE,
            categoryName: '',
            categoryCode: '',
            directDeliveryAmount: '',
            directDeliveryRange: '',
            directDeliveryRangeStr: '',
            expenseRatio: '',
            cityCodeList: [],
            provinceCityList: [],
            remark: '',
          }
        )
      }
    },
    // 删除行
    handleDelete (index) {
      this.tableInfo.list.splice(index, 1);
    },
    // 提交接口请求
    async submitAction () {
      const res = await submitStantardService(
        this.tableInfo.list,
        state => { this.submitLoading = state }
      );
      if (res?.data) {
        const { hasErrorMsg, data } = res.data
        if (hasErrorMsg) {
          this.$message.error('存在异常数据，请编辑后重新提交')
          this.initTableColumns()
          this.tableInfo.columns.unshift(ERRORS_COLUMN)
          this.tableInfo.list = data
        } else {
          this.submitSuccessCallback()
        }
      }
    },
    // 提交校验
    handleSubmit () {
      // 校验固定必填字段
      const requiredFields = this.tableInfo.columns.filter(item => item.required).map(item => item.key)
      let hasEmptyVal = false
      this.tableInfo.list.map((item) => {
        Object.keys(item).forEach(ele => {
          if (requiredFields.includes(ele) && item[ele] !== 0 && !item[ele]) {
            console.log(ele)
            hasEmptyVal = true;
          }
        })
      })
      if (hasEmptyVal) {
        return this.$message.warning('请完善必填字段')
      }
      this.submitAction()
    },
    submitSuccessCallback () {
      this.$message.success('操作成功')
      this.$router.push({ name: 'factoryStandardAudit' })
    },
    // 取消
    handleBack () {
      this.$router.go(-1)
    },
  }
};
</script>
<style scoped>
.el-scrollbar__wrap {
  overflow: auto;
  margin-bottom: 0px !important;
  margin-right: 0px !important;
}
</style>
